#include <glib.h>
#include <SDL.h>
#include "racanhack.h"
#include "task.h"
#include "video.h"
#include "cave.h"
#include "player.h"
#include "floor.h"
#include "los.h"

void los_trans_state(state (*fp)(struct _task *task), struct _los *los)
{
  if (los->task != NULL) los->task->alive = FALSE;
  los->task = task_add(fp, los);
}

gboolean is_los_onsight(struct _coord coord)
{
  return Los.onsight[coord.x][coord.y];
}

void los_init()
{
}

void los_free()
{
}

struct _los *los_add()
{
  struct _los *los;
  los = &Los;
  los->task = NULL;
  return los;
}

state los_update(struct _task *task)
{
  struct _los *los;
  struct _coord c[5];
  int i;
  struct _room *room;
  struct _coord p;
  los = (struct _los *)task->pointer[0];
  for (p.x = 0; p.x < MAP_W; p.x++) {
    for (p.y = 0; p.y < MAP_H; p.y++) {
      los->onsight[p.x][p.y] = FALSE;
    };
  };
  c[0].x = Player.coord.x;
  c[0].y = Player.coord.y;
  c[1].x = Player.coord.x - 1;
  c[1].y = Player.coord.y;
  c[2].x = Player.coord.x + 1;
  c[2].y = Player.coord.y;
  c[3].x = Player.coord.x;
  c[3].y = Player.coord.y - 1;
  c[4].x = Player.coord.x;
  c[4].y = Player.coord.y + 1;
  for (i = 0; i < 5; i++) {
    if ((c[i].x < 0) ||
	(c[i].y < 0) ||
	(c[i].x >= MAP_W) ||
	(c[i].y >= MAP_H)) continue;
    los->onsight[c[i].x][c[i].y] = TRUE;
    if (is_map_pass(c[i])) curf->cave.map[c[i].x][c[i].y].passed = TRUE;
  };
  room = at_room(Player.coord); 
  if (room != NULL) {
    for (p.x = room->lx - 1; p.x <= room->hx + 1; p.x++) {
      for (p.y = room->ly - 1; p.y <= room->hy + 1; p.y++) {
      if ((p.x < 0) ||
	  (p.y < 0) ||
	  (p.x >= MAP_W) ||
	  (p.y >= MAP_H)) continue;
	los->onsight[p.x][p.y] = TRUE;
	if (is_map_pass(p)) curf->cave.map[p.x][p.y].passed = TRUE;
      };
    };
  };
  los->task->alive = FALSE;
  los->task = NULL;
  return;
}
